//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package cn.com.jit.assp.ias.sp.saml11.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.example.demo.props.PkiProperties;

import cn.com.jit.assp.ias.saml.saml11.SAMLAttributes.SAMLAttributeName;
import cn.com.jit.assp.ias.sp.saml11.config.bean.AgentSet;
import cn.com.jit.assp.ias.sp.saml11.config.bean.Gateway;
import cn.com.jit.assp.ias.sp.saml11.config.bean.J2EEAgentSet;
import cn.com.jit.assp.ias.sp.saml11.config.bean.SelfExpOid;
import cn.com.jit.assp.ias.sp.saml11.config.bean.WorkFlowSet;
import cn.com.jit.assp.ias.sp.saml11.config.util.GatewayList;
import cn.com.jit.cinas.commons.session.MemorySessionManager;

@Component
public final class XMLConfiguration extends BaseConfiguration {
    private static final Log logger = LogFactory.getLog(XMLConfiguration.class);
    private static final String KEY_AGENTSETTINGS_OFFLINESTRATEGY = "OffLineStrategy";
    private static final String KEY_AGENTSETTINGS_OFFLINESTRATEGY_ENABLE = "Enable";
    private static final String KEY_AGENTSETTINGS_ACCESSWHENNOGATEWAYAVAILABLE = "AccessWhenNoGatewayAvailable";
    private static final String KEY_AGENTSETTINGS_TESTPERIOD = "TestPeriod";
    private static final String KEY_AGENTSETTINGS_TOKENSETTINGS_MAXDISCREPANCY = "MaxDiscrepancy";
    private static final String KEY_AGENTSETTINGS_LOCALSESSION_MAXIDLETIME = "MaxIdleTime";
    private static final String KEY_AGENTSETTINGS_LOCALSESSION_LIVETIME = "LiveTime";
    private static final String KEY_AGENTSETTINGS_LOCALSESSION_COOKIE_DOMAIN = "Domain";
    private static final String KEY_AGENTSETTINGS_LOCALSESSION_COOKIE_SECURE = "Secure";
    private static final String KEY_AGENTSETTINGS_LOCALSESSION_COOKIE_PATH = "Path";
    private static final String KEY_J2EEAGENTSETTIONG_VERSION = "Version";
    private static final String KEY_J2EEAGENTSETTIONG_USERINFOKEYNAME = "UserInfoKeyName";
    private static final String KEY_J2EEAGENTSETTIONG_USERINFOSCOPE = "UserInfoScope";
    private static final String KEY_J2EEAGENTSETTIONG_ERRORPAGE = "ErrorPage";
    private static final String KEY_J2EEAGENTSETTIONG_OUTPUTDEBUG = "OutputDebugLog";
    private static final String KEY_J2EEAGENTSETTIONG_NOTAUTHENTICATE = "NotAuthenticate";
    private static final String KEY_J2EEAGENTSETTIONG_NOTAUTHENTICATE_URI = "URI";
    private static final String KEY_GATEWAYLIST_GATEWAY = "Gateway";
    private static final String KEY_GATEWAYLIST_GATEWAY_AVAILABLETESTING = "AvailableTesting";
    private static final String KEY_GATEWAYLIST_GATEWAY_AVAILABLETESTING_CORRECTACK = "CorrectAck";
    private static final String KEY_GATEWAYLIST_GATEWAY_LOGINURL = "LoginURL";
    private static final String KEY_GATEWAYLIST_GATEWAY_IDPQUERY = "IdpQuery";
    private static final String KEY_GATEWAYLIST_GATEWAY_IDPQUERY_IDPURL = "IdpUrl";
    private static final String KEY_GATEWAYLIST_GATEWAY_INSURANCE_NUMBER_IFPARSING = "InsuranceNumberParsing";
    private static final String KEY_GATEWAYLIST_GATEWAY_ICREGISTRATION_NUMBER_IFPARSING = "ICRegistrationNumberParsing";
    private static final String KEY_GATEWAYLIST_GATEWAY_TAXATION_NUMBER_IFPARSING = "TaxationNumberParsing";
    private static final String KEY_GATEWAYLIST_GATEWAY_ORGANIZATION_NUMBER_IFPARSING = "OrganizationCodeParsing";
    private static final String KEY_GATEWAYLIST_GATEWAY_IDENTIFYCODE_NUMBER_IFPARSING = "IdentifyCodeParsing";
    private static final String KEY_GATEWAYLIST_GATEWAY_SELFEXP_IFPARSING = "SelfExpParsing";
    private static final String KEY_GATEWAYLIST_GATEWAY_SELFEXP_OID = "selfExpOid";
    private static final XMLConfiguration instance = new XMLConfiguration();
    private Document document;

    private XMLConfiguration() {}

    public static final XMLConfiguration getInstance() {
        return instance;
    }

    public final synchronized void configure(Document doc, PkiProperties pkiProperties) throws AgentConfigException {
        this.document = doc;
        Element root = this.document.getDocumentElement();
        this.parseAgentSet(root);
        this.parseGatewayList(root, pkiProperties);
        this.parseJ2EEAgentSet(root);
        this.parseWorkFlowSet(root);
        this.parseUserInfoScope();
    }

    private void parseWorkFlowSet(Element root) throws AgentConfigException {
        WorkFlowSet work = new WorkFlowSet();
        List<SAMLAttributeName> attributes = new ArrayList();
        NodeList nodes = root.getElementsByTagName("WorkFlowSettings");
        Element e = (Element)nodes.item(0);
        String s = ((Element)e.getElementsByTagName("AccessControl").item(0)).getAttribute("CheckAccessAuthority");
        work.setCheckAccessAuthority(Boolean.valueOf(s));
        s = ((Element)e.getElementsByTagName("UserAttributes").item(0)).getAttribute("Query");
        if ("all".equals(s)) {
            work.setQuery("ALL");
        } else if ("portion".equals(s)) {
            work.setQuery("PORTION");
        } else {
            work.setQuery("NONE");
        }

        nodes = e.getElementsByTagName("Attr");

        String ifICRegistrationNumber;
        String ifTaxationNumber;
        for (int i = 0; i < nodes.getLength(); ++i) {
            if (nodes.item(i) instanceof Element) {
                Element el = (Element)nodes.item(i);
                ifICRegistrationNumber = el.getAttribute("name");
                ifTaxationNumber = el.getAttribute("namespace");
                SAMLAttributeName samlName = new SAMLAttributeName(ifICRegistrationNumber, ifTaxationNumber);
                attributes.add(samlName);
            }
        }

        work.setQueryList(attributes);
        List<SelfExpOid> selfExpOids = new ArrayList();
        String ifInsuranceNumber =
            ((Element)e.getElementsByTagName("InsuranceNumberParsing").item(0)).getAttribute("Enable");
        ifICRegistrationNumber =
            ((Element)e.getElementsByTagName("ICRegistrationNumberParsing").item(0)).getAttribute("Enable");
        ifTaxationNumber = ((Element)e.getElementsByTagName("TaxationNumberParsing").item(0)).getAttribute("Enable");
        String ifOrganizationCode =
            ((Element)e.getElementsByTagName("OrganizationCodeParsing").item(0)).getAttribute("Enable");
        String ifIdentifyCode = ((Element)e.getElementsByTagName("IdentifyCodeParsing").item(0)).getAttribute("Enable");
        String ifSelfExpParsing = ((Element)e.getElementsByTagName("SelfExpParsing").item(0)).getAttribute("Enable");
        nodes = e.getElementsByTagName("selfExpOid");

        for (int i = 0; i < nodes.getLength(); ++i) {
            String value = nodes.item(i).getFirstChild().getNodeValue();
            Element el = (Element)nodes.item(i);
            String name = el.getAttribute("name");
            String namespace = el.getAttribute("namespace");
            selfExpOids.add(new SelfExpOid(name, namespace, value));
        }

        work.setSelfExpOids(selfExpOids);
        work.setInsuranceNumberParsing("true".equalsIgnoreCase(ifInsuranceNumber));
        work.setICRegistrationNumberParsing("true".equalsIgnoreCase(ifICRegistrationNumber));
        work.setTaxationNumberParsing("true".equalsIgnoreCase(ifTaxationNumber));
        work.setOrganizationCodeParsing("true".equalsIgnoreCase(ifOrganizationCode));
        work.setIdentifyCodeParsing("true".equalsIgnoreCase(ifIdentifyCode));
        work.setParseSelfCertExp("true".equalsIgnoreCase(ifSelfExpParsing));
        this.workFlowSet = work;
    }

    private void parseUserInfoScope() {
        String scope = this.getJ2EEAgentSet().getUserInfoScope();
        if (logger.isDebugEnabled()) {
            logger.debug("UserInfoScope = [" + scope + "]");
        }

        if (scope.equalsIgnoreCase("request")) {
            this.useSessionScope = false;
        } else {
            this.useSessionScope = true;
        }

    }

    private void parseGatewayList(Element root, PkiProperties pkiProperties) throws AgentConfigException {
        this.gatewayList = new GatewayList();
        NodeList list = root.getElementsByTagName("Gateway");

        for (int i = 0; i < list.getLength(); ++i) {
            if (list.item(i) instanceof Element) {
                Element e = (Element)list.item(i);
                int order = Integer.parseInt(e.getAttribute("order"));
                NodeList nodes = e.getElementsByTagName("AvailableTesting");
                String availableTesting = nodes.item(0).getFirstChild().getNodeValue();
                String correctAck = null;
                if (nodes.item(0) instanceof Element) {
                    Element ee = (Element)nodes.item(0);
                    correctAck = ee.getAttribute("CorrectAck");
                }

                nodes = e.getElementsByTagName("LoginURL");
                String loginURL = nodes.item(0).getFirstChild().getNodeValue();
                nodes = e.getElementsByTagName("IdpQuery");
                Element idpurl = (Element)nodes.item(0);
                nodes = idpurl.getElementsByTagName("IdpUrl");
                Object var11 = null;

                try {
                    new URI(loginURL, true);
                } catch (URIException var17) {
                    throw new AgentConfigException(
                        "The " + loginURL + " is not URI Object. please check  " + loginURL + " value.");
                }

                List<String> idpQueryList = new ArrayList();

                for (int j = 0; nodes != null && j < nodes.getLength(); ++j) {
                    String idpQuery = nodes.item(j).getFirstChild().getNodeValue();

                    try {
                        new URI(idpQuery, true);
                    } catch (URIException var16) {
                        throw new AgentConfigException(
                            "The " + idpQuery + " is not a URI Object. please check  " + idpQuery + " value.");
                    }

                    this.artifactMapper.putSourceUrl(idpQuery);
                    idpQueryList.add(idpQuery);
                }

                if (pkiProperties != null) {
                    correctAck = pkiProperties.getCorrectAck();
                    idpQueryList = pkiProperties.getIdpQueryList();
                    loginURL = pkiProperties.getLoginURL();
                }

                Gateway gateway = new Gateway();
                gateway.setAvailableTesting(availableTesting);
                gateway.setCorrectAck(correctAck);
                gateway.setIdpQuery(idpQueryList);
                gateway.setLoginURL(loginURL);
                gateway.setUsed(false);
                gateway.setOrder(order);
                this.gatewayList.add(gateway);
            }
        }

    }

    private void parseJ2EEAgentSet(Element root) throws AgentConfigException {
        String version = null;
        String userInfoKeyName = null;
        String userInfoScope = null;
        String errorPage = null;
        boolean debug = false;
        NodeList nodes = root.getElementsByTagName("Version");
        Element e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            version = e.getFirstChild().getNodeValue();
        }

        nodes = root.getElementsByTagName("UserInfoKeyName");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            userInfoKeyName = e.getFirstChild().getNodeValue();
        }

        nodes = root.getElementsByTagName("UserInfoScope");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            userInfoScope = e.getFirstChild().getNodeValue();
        }

        nodes = root.getElementsByTagName("ErrorPage");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            errorPage = e.getFirstChild().getNodeValue();
        }

        nodes = root.getElementsByTagName("OutputDebugLog");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            String outputDebugLog = e.getFirstChild().getNodeValue();
            debug = Boolean.valueOf(outputDebugLog);
        }

        this.j2EEAgentSet = new J2EEAgentSet(version, userInfoKeyName, userInfoScope, errorPage, debug);
        nodes = root.getElementsByTagName("NotAuthenticate");
        e = (Element)nodes.item(0);
        nodes = e.getElementsByTagName("URI");
        String[] notAuthenticate = new String[nodes.getLength()];

        for (int j = 0; nodes != null && j < nodes.getLength(); ++j) {
            String uri = nodes.item(j).getFirstChild().getNodeValue();
            notAuthenticate[j] = uri;
        }

        this.j2EEAgentSet.setNotAuthenticate(notAuthenticate);
    }

    private void parseAgentSet(Element root) throws AgentConfigException {
        boolean enable = false;
        String accessStrategy = null;
        int testPeriod = 0;
        int maxDiscrepancy = 0;
        int maxIdleTime = 0;
        int liveTime = 0;
        String domain = null;
        boolean secure = false;
        String path = null;
        NodeList nodes = root.getElementsByTagName("OffLineStrategy");
        Element e = (Element)nodes.item(0);
        enable = Boolean.valueOf(e.getAttribute("Enable"));
        nodes = root.getElementsByTagName("AccessWhenNoGatewayAvailable");
        e = (Element)nodes.item(0);
        String secyre;
        if (e.getFirstChild() != null) {
            secyre = e.getFirstChild().getNodeValue();
            if ("Permit".equals(secyre)) {
                accessStrategy = "Permit";
            } else if ("Deny".equals(secyre)) {
                accessStrategy = "Deny";
            }
        }

        nodes = root.getElementsByTagName("TestPeriod");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            secyre = e.getFirstChild().getNodeValue();
            testPeriod = Integer.parseInt(secyre);
        }

        nodes = root.getElementsByTagName("MaxDiscrepancy");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            secyre = e.getFirstChild().getNodeValue();
            maxDiscrepancy = Integer.parseInt(secyre);
        }

        nodes = root.getElementsByTagName("MaxIdleTime");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            secyre = e.getFirstChild().getNodeValue();
            maxIdleTime = Integer.parseInt(secyre);
        }

        nodes = root.getElementsByTagName("LiveTime");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            secyre = e.getFirstChild().getNodeValue();
            liveTime = Integer.parseInt(secyre);
        }

        nodes = root.getElementsByTagName("Domain");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            domain = e.getFirstChild().getNodeValue();
        }

        nodes = root.getElementsByTagName("Secure");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            secyre = e.getFirstChild().getNodeValue();
            secure = Boolean.getBoolean(secyre);
        }

        nodes = root.getElementsByTagName("Path");
        e = (Element)nodes.item(0);
        if (e.getFirstChild() != null) {
            path = e.getFirstChild().getNodeValue();
        }

        this.agentSet = new AgentSet(enable, accessStrategy, testPeriod, maxDiscrepancy, maxIdleTime, liveTime, domain,
            secure, path);
        this.sessionManager = new MemorySessionManager(-1, maxIdleTime, liveTime);
    }
}
